import { ChangeDetectorRef, Component, ElementRef, Input, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms';

import { OptionsInterface } from '@app/core/services/types';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzFormModule } from 'ng-zorro-antd/form';

import dataTypes from '../datatype-config';
import { SharedModule } from '@app/shared/shared.module';
import { NzDrawerModule } from 'ng-zorro-antd/drawer';

@Component({
  selector: 'app-config-panel',
  standalone: true,
  imports: [FormsModule, NzFormModule, ReactiveFormsModule, SharedModule, NzDrawerModule],
  templateUrl: './config-panel.component.html',
  styleUrl: './config-panel.component.less'
})
export class ConfigPanelComponent implements OnInit {
  _isDisplay: boolean = false;
  datatypeList: OptionsInterface[] = [];
  dataFieldList: OptionsInterface[] = [];
  validateForm!: FormGroup;

  /**
   * Defines if drop is enabled. `true` by default.
   */
  @Input() set isDisplay(value: boolean) {
    const configPanel: HTMLElement = document.querySelector('.right-panel')!;
    this._isDisplay = value;

    if (configPanel) {
      if (this._isDisplay === true) {
        configPanel.classList.toggle('drawer-open');
      } else {
        configPanel.classList.remove('drawer-open');
      }
    }
  }

  constructor(
    private readonly cdr: ChangeDetectorRef,
    private readonly fb: FormBuilder
  ) {}

  ngOnInit(): void {
    this.initDatatypeList();
    this.validateForm = this.fb.group({
      datatypeId: new FormControl(null, {
        asyncValidators: [],
        updateOn: 'blur'
      }),
      fieldName: new FormControl(null, {
        asyncValidators: [],
        updateOn: 'blur',
        validators: []
      })
    });
  }

  showConfigPanel(): void {
    this._isDisplay = false;
  }

  initDatatypeList(): void {
    const keys = Object.keys(dataTypes);
    this.datatypeList = keys.map((key, index) => {
      return {
        value: index,
        label: key
      };
    });
  }

  datatypeChange(datatypeId: number): void {
    const keys = Object.keys(dataTypes);
    const currentDatatype = keys[datatypeId];
    // @ts-ignore
    const dataFields: NzSafeAny[] = dataTypes[currentDatatype].columns;
    this.dataFieldList = [{ value: 'none', label: '请选择' }];
    this.dataFieldList.concat(
      dataFields.map(r => {
        return {
          value: r.field,
          label: r.title
        };
      })
    );
    this.cdr.markForCheck();
  }
}
